<template>
  <div class="table-config-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>数据表信息</span>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form :inline="true" :model="queryForm" class="mb-4">
        <el-form-item label="表名">
          <el-input
            v-model="queryForm.table_name"
            placeholder="请输入表名"
            clearable
            class="!w-[180px]"
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="queryForm.description"
            placeholder="请输入描述"
            clearable
            class="!w-[180px]"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon class="mr-2"><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetForm">
            <el-icon class="mr-2"><Refresh /></el-icon>重置
          </el-button>
          <el-button type="info" @click="showQueryRange">
            <el-icon class="mr-2"><View /></el-icon>可查范围
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格信息列表 -->
      <PureTable
        row-key="id"
        :data="tableList"
        :columns="tableColumns"
        :loading="loading"
        :pagination="tablePagination"
        border
        @page-size-change="onTableSizeChange"
        @page-current-change="onTableCurrentChange"
      >
        <template #operation="{ row }">
          <el-tag
            class="mx-1 cursor-pointer"
            type="primary"
            effect="plain"
            @click="handleEditFields(row)"
          >
            修改表字段
          </el-tag>
        </template>
      </PureTable>
    </el-card>

    <!-- 修改表字段对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="'修改表字段 - ' + currentTable?.description"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="fields-dialog-content">
        <div class="dialog-header">
          <el-button type="primary" @click="handleAddField">
            <el-icon class="mr-2"><Plus /></el-icon>新增字段
          </el-button>
        </div>

        <!-- 字段查询表单 -->
        <el-form :inline="true" :model="fieldQueryForm" class="mb-4">
          <el-form-item label="字段名">
            <el-input
              v-model="fieldQueryForm.field_id"
              placeholder="请输入字段名"
              clearable
              class="!w-[180px]"
            />
          </el-form-item>
          <el-form-item label="字段类型">
            <el-input
              v-model="fieldQueryForm.type"
              placeholder="请输入字段类型"
              clearable
              class="!w-[180px]"
            />
          </el-form-item>
          <el-form-item label="显示名称">
            <el-input
              v-model="fieldQueryForm.label"
              placeholder="请输入显示名称"
              clearable
              class="!w-[180px]"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFieldQuery">
              <el-icon class="mr-2"><Search /></el-icon>查询
            </el-button>
            <el-button @click="resetFieldForm">
              <el-icon class="mr-2"><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>

        <div class="table-container">
          <el-table
            v-loading="fieldsLoading"
            :data="fieldsList"
            border
            style="width: 100%"
          >
            <el-table-column
              prop="field_id"
              label="字段ID"
              width="80"
              align="center"
            />
            <el-table-column
              prop="field"
              label="字段名"
              min-width="120"
              align="center"
            />
            <el-table-column
              prop="type"
              label="字段类型"
              width="100"
              align="center"
            />
            <el-table-column
              prop="label"
              label="显示名称"
              min-width="120"
              align="center"
            />
            <el-table-column
              prop="must"
              label="是否必填"
              width="100"
              align="center"
            />
            <el-table-column
              prop="rank"
              label="排序"
              width="80"
              align="center"
            />
            <el-table-column
              prop="view_permission_name"
              label="查看权限"
              min-width="150"
              align="center"
            />
            <el-table-column
              prop="set_permission_name"
              label="修改权限"
              min-width="150"
              align="center"
            />
            <el-table-column
              prop="created_at"
              label="创建时间"
              width="160"
              align="center"
            />
            <el-table-column
              prop="updated_at"
              label="更新时间"
              width="160"
              align="center"
            />
            <el-table-column
              label="操作"
              width="120"
              align="center"
              fixed="right"
            >
              <template #default="{ row }">
                <el-tag
                  class="mx-1 cursor-pointer"
                  type="warning"
                  effect="plain"
                  @click="handleEditField(row)"
                >
                  修改字段
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 字段分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="fieldPagination.currentPage"
            v-model:page-size="fieldPagination.pageSize"
            :page-sizes="fieldPagination.pageSizes"
            :total="fieldPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="onFieldSizeChange"
            @current-change="onFieldCurrentChange"
          />
        </div>
      </div>
    </el-dialog>

    <!-- 新增字段对话框 -->
    <el-dialog
      v-model="addFieldDialogVisible"
      title="新增字段"
      width="500px"
      :close-on-click-modal="false"
      class="add-field-dialog"
    >
      <el-form
        ref="addFieldFormRef"
        :model="addFieldForm"
        :rules="addFieldRules"
        label-width="80px"
      >
        <el-form-item label="字段名" prop="field">
          <el-input v-model="addFieldForm.field" placeholder="请输入字段名" />
        </el-form-item>
        <el-form-item label="显示名称" prop="label">
          <el-input v-model="addFieldForm.label" placeholder="请输入显示名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addFieldDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddField">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改字段对话框 -->
    <el-drawer
      v-model="editFieldDialogVisible"
      :title="'修改字段 - ' + currentTable?.description"
      size="500px"
      :close-on-click-modal="false"
      direction="rtl"
      class="edit-field-drawer"
    >
      <el-form
        ref="editFieldFormRef"
        :model="editFieldForm"
        :rules="addFieldRules"
        label-width="80px"
        class="px-4"
      >
        <el-form-item label="字段名">
          <el-input v-model="editFieldForm.field" disabled />
        </el-form-item>
        <el-form-item label="字段类型">
          <el-select
            v-model="editFieldForm.type"
            placeholder="请选择字段类型"
            class="w-full"
          >
            <el-option label="文本" value="str" />
            <el-option label="数字" value="int" />
            <el-option label="枚举" value="enum" />
          </el-select>
        </el-form-item>

        <!-- 枚举值输入区域 -->
        <el-form-item v-if="editFieldForm.type === 'enum'" label="枚举值">
          <div class="enum-tags">
            <el-tag
              v-for="(tag, index) in enumTags"
              :key="index"
              closable
              :disable-transitions="false"
              class="mx-1"
              @close="handleCloseTag(index)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="enumInputVisible"
              ref="enumInputRef"
              v-model="enumInputValue"
              class="w-[100px] ml-1"
              size="small"
              @keyup.enter="handleEnumInputConfirm"
              @blur="handleEnumInputConfirm"
            />
            <el-button
              v-else
              class="button-new-tag ml-1"
              size="small"
              @click="showEnumInput"
            >
              + 添加枚举值
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="显示名称" prop="label">
          <el-input
            v-model="editFieldForm.label"
            placeholder="请输入显示名称"
          />
        </el-form-item>
        <el-form-item label="是否必填">
          <el-select v-model="editFieldForm.must" class="w-full">
            <el-option label="必须" value="必须" />
            <el-option label="非必须" value="非必须" />
            <el-option label="排除" value="排除" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number
            v-model="editFieldForm.rank"
            :min="0"
            :max="999"
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="表格配置">
          <div class="config-form">
            <el-form-item label="列宽度" prop="config.width">
              <el-input-number
                v-model="editFieldForm.config.width"
                :min="50"
                :max="500"
                placeholder="请输入列宽度"
              />
            </el-form-item>
            <el-form-item label="对齐方式" prop="config.align">
              <el-select
                v-model="editFieldForm.config.align"
                placeholder="请选择对齐方式"
                class="w-full"
              >
                <el-option label="居左" value="left" />
                <el-option label="居中" value="center" />
                <el-option label="居右" value="right" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否显示">
              <el-switch
                v-model="editFieldForm.config.visible"
                :active-value="true"
                :inactive-value="false"
              />
            </el-form-item>

            <!-- 自定义配置 -->
            <div class="custom-config">
              <div class="custom-config-header">
                <span>自定义配置</span>
                <el-button type="primary" link @click="addCustomConfig">
                  <el-icon class="mr-1"><Plus /></el-icon>添加配置
                </el-button>
              </div>
              <div
                v-for="(_, index) in editFieldForm.customConfigs"
                :key="index"
                class="custom-config-item"
              >
                <el-input
                  v-model="editFieldForm.customConfigs[index].key"
                  placeholder="配置键"
                  class="config-key"
                />
                <el-input
                  v-model="editFieldForm.customConfigs[index].value"
                  placeholder="配置值"
                  class="config-value"
                />
                <el-button
                  type="danger"
                  link
                  @click="removeCustomConfig(index)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end px-4 py-2 border-t">
          <el-button @click="editFieldDialogVisible = false">取消</el-button>
          <el-button type="primary" class="ml-2" @click="submitEditField"
            >确定</el-button
          >
        </div>
      </template>
    </el-drawer>

    <!-- 可查范围弹窗 -->
    <el-dialog
      v-model="queryRangeDialogVisible"
      title="可查范围"
      width="80%"
      :close-on-click-modal="false"
    >
      <!-- 表格切换标签 -->
      <div class="table-tags mb-4">
        <el-tag
          v-for="table in myTables"
          :key="table.id"
          :type="currentTableId === table.id ? 'primary' : 'info'"
          class="mr-2 cursor-pointer"
          effect="plain"
          @click="handleTableChange(table.id)"
        >
          {{ table.description }}
        </el-tag>
      </div>

      <el-table
        v-loading="scopeLoading"
        :data="scopeList"
        border
        style="width: 100%"
      >
        <el-table-column prop="name" label="角色名称" align="center" />
        <el-table-column prop="description" label="角色描述" align="center" />
        <el-table-column prop="field" label="字段名" align="center" />
        <el-table-column prop="label" label="显示名称" align="center" />
        <el-table-column
          prop="type"
          label="字段类型"
          align="center"
          width="100"
        />
        <el-table-column label="可查范围" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.scope" type="success" effect="plain">
              {{ formatScope(row.scope) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="created_at"
          label="创建时间"
          align="center"
          width="160"
        />
        <el-table-column
          prop="updated_at"
          label="更新时间"
          align="center"
          width="160"
        />
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="scopePagination.currentPage"
          v-model:page-size="scopePagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="scopePagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="onScopeSizeChange"
          @current-change="onScopeCurrentChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from "element-plus";
import {
  Search,
  Refresh,
  UserFilled,
  Plus,
  Delete,
  View
} from "@element-plus/icons-vue";
import {
  getAdminerList,
  getAllRoles,
  setAdminerRole,
  setAdminerStatus,
  getTableByPage,
  getTableInfoByPage,
  addTableFiled,
  updateTableField,
  setTableFiled,
  getTableFieldScopeAll,
  getMyTable
} from "@/api/index";
import PureTable from "@pureadmin/table";

interface TableInfo {
  id: number;
  name: string;
  created_at: string;
  updated_at: string;
  description: string;
}

interface TableField {
  field_id: number;
  table_id: number;
  table_name: string;
  field: string;
  type: string;
  view_permission: number;
  view_permission_name: string;
  set_permission: number;
  set_permission_name: string;
  created_at: string;
  updated_at: string;
  config: string;
  label: string;
  must: string;
  rank: number;
}

interface CustomConfig {
  key: string;
  value: string;
}

const loading = ref(false);
const tableList = ref<TableInfo[]>([]);
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const formRef = ref<FormInstance>();
const fieldsLoading = ref(false);
const fieldsList = ref<TableField[]>([]);
const currentTable = ref<TableInfo | null>(null);

// 表格分页配置
const tablePagination = reactive({
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 15, 20],
  total: 0,
  align: "right",
  background: true,
  size: "default"
});

// 查询表单数据
const queryForm = reactive({
  table_name: "",
  description: ""
});

// 字段查询表单数据
const fieldQueryForm = reactive({
  field_id: "",
  type: "",
  label: ""
});

// 字段分页配置
const fieldPagination = reactive({
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 15, 20],
  total: 0,
  align: "right",
  background: true,
  size: "default"
});

// 新增字段相关
const addFieldDialogVisible = ref(false);
const addFieldFormRef = ref<FormInstance>();
const addFieldForm = reactive({
  field: "",
  label: "",
  type: "str"
});

// 新增字段表单验证规则
const addFieldRules = {
  field: [
    { required: true, message: "请输入字段名", trigger: "blur" },
    {
      pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/,
      message: "字段名只能包含字母、数字和下划线，且必须以字母或下划线开头",
      trigger: "blur"
    }
  ],
  label: [{ required: true, message: "请输入显示名称", trigger: "blur" }]
};

// 处理新增字段
const handleAddField = () => {
  addFieldForm.field = "";
  addFieldForm.label = "";
  addFieldForm.type = "str";
  addFieldDialogVisible.value = true;
};

// 提交新增字段
const submitAddField = async () => {
  if (!addFieldFormRef.value || !currentTable.value) return;

  await addFieldFormRef.value.validate(async valid => {
    if (valid) {
      try {
        const data = {
          table_id: currentTable.value.id,
          field: addFieldForm.field,
          label: addFieldForm.label,
          type: addFieldForm.type
        };
        const res = await addTableFiled(data);
        if (res.status === "success") {
          ElMessage.success("新增字段成功");
          addFieldDialogVisible.value = false;
          // 刷新字段列表
          fetchTableFields(currentTable.value.id);
        }
      } catch (error) {
        console.error("新增字段失败:", error);
        ElMessage.error("新增字段失败");
      }
    }
  });
};

// 获取表格字段配置列表
const fetchTableFields = async (tableId: number) => {
  fieldsLoading.value = true;
  try {
    const params = {
      page: fieldPagination.currentPage,
      size: fieldPagination.pageSize,
      table_id: tableId,
      field_name: fieldQueryForm.field_id || undefined,
      type: fieldQueryForm.type || undefined,
      label: fieldQueryForm.label || undefined
    };

    const res = await getTableByPage(params);
    if (res.status === "success") {
      fieldsList.value = res.data.records;
      fieldPagination.total = res.data.pagination.total;
    }
  } catch (error) {
    console.error("获取表格字段配置失败:", error);
    ElMessage.error("获取表格字段配置失败");
  } finally {
    fieldsLoading.value = false;
  }
};

// 重置字段查询表单
const resetFieldForm = () => {
  Object.keys(fieldQueryForm).forEach(key => {
    fieldQueryForm[key] = "";
  });
  fieldPagination.currentPage = 1;
  if (currentTable.value) {
    fetchTableFields(currentTable.value.id);
  }
};

// 字段查询方法
const handleFieldQuery = () => {
  fieldPagination.currentPage = 1;
  if (currentTable.value) {
    fetchTableFields(currentTable.value.id);
  }
};

const onFieldSizeChange = (val: number) => {
  fieldPagination.pageSize = val;
  if (currentTable.value) {
    fetchTableFields(currentTable.value.id);
  }
};

const onFieldCurrentChange = (val: number) => {
  fieldPagination.currentPage = val;
  if (currentTable.value) {
    fetchTableFields(currentTable.value.id);
  }
};

// 重置表单
const resetForm = () => {
  Object.keys(queryForm).forEach(key => {
    queryForm[key] = "";
  });
  tablePagination.currentPage = 1;
  fetchTableInfo();
};

// 查询方法
const handleQuery = () => {
  tablePagination.currentPage = 1;
  fetchTableInfo();
};

const onTableSizeChange = (val: number) => {
  tablePagination.pageSize = val;
  fetchTableInfo();
};

const onTableCurrentChange = (val: number) => {
  tablePagination.currentPage = val;
  fetchTableInfo();
};

// 获取表格信息列表
const fetchTableInfo = async () => {
  loading.value = true;
  try {
    const params = {
      page: tablePagination.currentPage,
      size: tablePagination.pageSize,
      table_name: queryForm.table_name || undefined,
      description: queryForm.description || undefined
    };

    const res = await getTableInfoByPage(params);
    if (res.status === "success") {
      tableList.value = res.data.records;
      tablePagination.total = res.data.pagination.total;
    }
  } catch (error) {
    console.error("获取表格信息失败:", error);
    ElMessage.error("获取表格信息失败");
  } finally {
    loading.value = false;
  }
};

// 处理修改表字段
const handleEditFields = async (row: TableInfo) => {
  currentTable.value = row;
  dialogVisible.value = true;
  await fetchTableFields(row.id);
};

// 定义表格列
const tableColumns = [
  {
    label: "表ID",
    prop: "id",
    width: 80,
    align: "center"
  },
  {
    label: "表名",
    prop: "name",
    minWidth: 120,
    align: "center"
  },
  {
    label: "描述",
    prop: "description",
    minWidth: 150,
    align: "center"
  },
  {
    label: "创建时间",
    prop: "created_at",
    width: 160,
    align: "center"
  },
  {
    label: "更新时间",
    prop: "updated_at",
    width: 160,
    align: "center"
  },
  {
    label: "操作",
    slot: "operation",
    width: 120,
    fixed: "right",
    align: "center"
  }
];

const editFieldDialogVisible = ref(false);
const editFieldFormRef = ref<FormInstance>();
const editFieldForm = reactive({
  field_id: 0,
  field: "",
  label: "",
  type: "",
  config: {
    width: 120,
    align: "center",
    visible: true
  },
  customConfigs: [] as CustomConfig[],
  must: "必须",
  rank: 0
});

// 枚举相关
const enumTags = ref<string[]>([]);
const enumInputVisible = ref(false);
const enumInputValue = ref("");
const enumInputRef = ref<InstanceType<typeof ElInput>>();

// 显示枚举输入框
const showEnumInput = () => {
  enumInputVisible.value = true;
  nextTick(() => {
    enumInputRef.value?.input?.focus();
  });
};

// 处理枚举输入确认
const handleEnumInputConfirm = () => {
  if (enumInputValue.value) {
    enumTags.value.push(enumInputValue.value);
  }
  enumInputVisible.value = false;
  enumInputValue.value = "";
};

// 删除枚举标签
const handleCloseTag = (index: number) => {
  enumTags.value.splice(index, 1);
};

// 添加自定义配置
const addCustomConfig = () => {
  editFieldForm.customConfigs.push({ key: "", value: "" });
};

// 移除自定义配置
const removeCustomConfig = (index: number) => {
  editFieldForm.customConfigs.splice(index, 1);
};

// 处理修改字段
const handleEditField = (row: TableField) => {
  editFieldForm.field_id = row.field_id;
  editFieldForm.field = row.field;
  editFieldForm.label = row.label;
  editFieldForm.type = row.type;
  editFieldForm.customConfigs = [];
  editFieldForm.must = row.must;
  editFieldForm.rank = row.rank;

  // 默认清空枚举值
  enumTags.value = [];

  // 解析枚举值
  if (row.type.startsWith("enum")) {
    editFieldForm.type = "enum";
    const enumMatch = row.type.match(/enum\((.*)\)/);
    if (enumMatch) {
      const enumValues = enumMatch[1]
        .split(",")
        .map(v => v.replace(/^"|"$/g, "").replace(/^'|'$/g, ""));
      enumTags.value = enumValues;
    }
  }

  // 解析已有的配置
  if (row.config) {
    try {
      const config = JSON.parse(row.config);
      editFieldForm.config = {
        width: config.width || 120,
        align: config.align || "center",
        visible: config.visible !== undefined ? config.visible : true
      };

      // 提取自定义配置
      const reservedKeys = ["width", "align", "visible"];
      Object.entries(config).forEach(([key, value]) => {
        if (!reservedKeys.includes(key)) {
          editFieldForm.customConfigs.push({
            key,
            value: typeof value === "string" ? value : JSON.stringify(value)
          });
        }
      });
    } catch (error) {
      editFieldForm.config = {
        width: 120,
        align: "center",
        visible: true
      };
    }
  } else {
    editFieldForm.config = {
      width: 120,
      align: "center",
      visible: true
    };
  }

  editFieldDialogVisible.value = true;
};

// 提交修改字段
const submitEditField = async () => {
  if (!editFieldFormRef.value || !currentTable.value) return;

  await editFieldFormRef.value.validate(async valid => {
    if (valid) {
      try {
        // 合并基础配置和自定义配置
        const finalConfig = { ...editFieldForm.config };
        editFieldForm.customConfigs.forEach(({ key, value }) => {
          if (key.trim()) {
            try {
              finalConfig[key] = JSON.parse(value);
            } catch {
              finalConfig[key] = value;
            }
          }
        });

        // 处理枚举类型
        let finalType = editFieldForm.type;
        if (editFieldForm.type === "enum" && enumTags.value.length > 0) {
          const enumValues = enumTags.value.map(tag => `"${tag}"`).join(",");
          finalType = `enum(${enumValues})`;
        }

        const data = {
          id: editFieldForm.field_id,
          label: editFieldForm.label,
          type: finalType,
          config: finalConfig,
          must: editFieldForm.must,
          rank: editFieldForm.rank
        };
        const res = await setTableFiled(data);
        if (res.status === "success") {
          ElMessage.success("修改字段成功");
          editFieldDialogVisible.value = false;
          // 刷新字段列表
          fetchTableFields(currentTable.value.id);
        }
      } catch (error) {
        console.error("修改字段失败:", error);
        ElMessage.error("修改字段失败");
      }
    }
  });
};

// 可查范围相关
const queryRangeDialogVisible = ref(false);
const scopeLoading = ref(false);
const scopeList = ref([]);
const myTables = ref([]);
const currentTableId = ref(0);
const scopePagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 格式化scope字段
const formatScope = (scope: string) => {
  try {
    const scopeArray = JSON.parse(scope);
    return Array.isArray(scopeArray) ? scopeArray.join(", ") : scope;
  } catch {
    return scope;
  }
};

// 获取我的表格列表
const fetchMyTables = async () => {
  try {
    const res = await getMyTable();
    if (res.status === "success") {
      myTables.value = res.data;
      if (res.data.length > 0) {
        currentTableId.value = res.data[0].id;
        fetchScopeData();
      }
    }
  } catch (error) {
    console.error("获取表格列表失败:", error);
    ElMessage.error("获取表格列表失败");
  }
};

// 处理表格切换
const handleTableChange = (tableId: number) => {
  currentTableId.value = tableId;
  scopePagination.currentPage = 1;
  fetchScopeData();
};

// 获取可查范围数据
const fetchScopeData = async () => {
  if (!currentTableId.value) return;

  scopeLoading.value = true;
  try {
    const params = {
      page: scopePagination.currentPage,
      size: scopePagination.pageSize,
      role_id: "",
      field_id: "",
      table_id: currentTableId.value
    };

    const res = await getTableFieldScopeAll(params);
    if (res.status === "success") {
      scopeList.value = res.data.records;
      scopePagination.total = res.data.pagination.total;
    }
  } catch (error) {
    console.error("获取可查范围失败:", error);
    ElMessage.error("获取可查范围失败");
  } finally {
    scopeLoading.value = false;
  }
};

// 分页大小改变
const onScopeSizeChange = (val: number) => {
  scopePagination.pageSize = val;
  fetchScopeData();
};

// 当前页改变
const onScopeCurrentChange = (val: number) => {
  scopePagination.currentPage = val;
  fetchScopeData();
};

// 显示可查范围弹窗
const showQueryRange = async () => {
  queryRangeDialogVisible.value = true;
  await fetchMyTables();
};

// 添加监听字段类型变化
watch(
  () => editFieldForm.type,
  newType => {
    if (newType !== "enum") {
      enumTags.value = [];
    }
  }
);

onMounted(() => {
  fetchTableInfo(); // 获取表格信息
});
</script>

<style lang="scss" scoped>
.table-config-container {
  padding: 20px;

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  :deep(.el-table) {
    // 表格基础样式
    .cell {
      padding: 8px 0;
      line-height: 1.5;
    }
    // 表头样式
    .el-table__header {
      th {
        height: 50px;
        font-weight: bold;
        color: var(--el-text-color-primary);
        background-color: var(--el-fill-color-light);
      }
    }
  }

  .mb-4 {
    margin-bottom: 1rem;
  }

  .mr-2 {
    margin-right: 0.5rem;
  }
}

.fields-dialog-content {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 300px);

  .dialog-header {
    padding: 0 0 16px;
  }

  .table-container {
    flex: 1;
    margin: 16px 0;
    overflow: auto;
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding: 16px 0 0;
  }
}

:deep(.el-dialog) {
  margin: 100px auto 0 !important;

  .el-dialog__body {
    height: calc(100vh - 200px);
    padding: 20px;
    overflow: hidden;
  }
}

.mx-1 {
  margin: 0 4px;
}

.cursor-pointer {
  cursor: pointer;
}

/* 新增字段对话框样式 */
:deep(.el-dialog.add-field-dialog) {
  .el-dialog__body {
    max-height: 60vh;
    padding: 20px;
    overflow-y: auto;
  }
}

/* 修改字段抽屉样式 */
:deep(.edit-field-drawer) {
  .el-drawer__header {
    padding: 16px 20px;
    margin-bottom: 0;
    border-bottom: 1px solid var(--el-border-color-lighter);
  }

  .el-drawer__body {
    padding: 20px 0;
  }

  .el-form {
    height: calc(100% - 60px);
    overflow-y: auto;
  }

  .config-form {
    padding: 16px;
    background-color: var(--el-fill-color-light);
    border-radius: 4px;

    .el-form-item {
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.custom-config {
  padding-top: 16px;
  margin-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);

  .custom-config-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;

    span {
      font-weight: bold;
      color: var(--el-text-color-primary);
    }
  }

  .custom-config-item {
    display: flex;
    gap: 8px;
    align-items: center;
    margin-bottom: 8px;

    .config-key {
      width: 150px;
    }

    .config-value {
      flex: 1;
    }
  }
}

.enum-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  padding: 4px 0;

  .el-tag {
    margin-right: 6px;
    margin-bottom: 6px;
  }

  .button-new-tag {
    margin-bottom: 6px;
  }
}
</style>
